package com.tledu.cyrus.filter;

import com.tledu.cyrus.core.AjaxResult;
import com.tledu.cyrus.utils.ResponseUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * @author cyrus
 */
@WebFilter("/*")
public class Login2Filter extends HttpFilter {

    private Set<String> unLoginPathSet;

    @Override
    public void init() throws ServletException {
        unLoginPathSet = new HashSet<String>();
        unLoginPathSet.add("/user/login");
        unLoginPathSet.add("/user/register");
    }

    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse resp, FilterChain chain) throws IOException, ServletException {
//        System.out.println("login2 放行之前。。。");
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        // /user
        String path = req.getServletPath();
        // /login
        String pathInfo = req.getPathInfo();
        if (pathInfo != null) {
            // /user/login
            path = path + pathInfo;
        }
        System.out.println("请求了：" + path);
        if (unLoginPathSet.contains(path)) {
            // 不需要登录就能访问的
            chain.doFilter(req, resp);
            return;
        }

        HttpSession session = req.getSession();
        if (session.getAttribute("user") == null) {
            // 没登陆
            ResponseUtils.responseJson(resp, AjaxResult.error(401, "请先登录"));
        } else {
            chain.doFilter(req, resp);
        }

//        System.out.println("login2 执行完成业务逻辑之后。。。");

    }
}
